package com.huangsm.cloud.consumer.controller;

import com.huangsm.cloud.consumer.entity.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.annotation.SessionScope;

import javax.annotation.Resource;

/**
 * 通过restTemplate方式调用服务+客户端负载均衡Ribbon
 *
 * @author huangsm
 * @version V1.0
 */
@RestController
@Slf4j
//@SessionScope
public class UserController {
    @Resource(name = "rest")
    private RestTemplate restTemplate;

    @GetMapping("/getUser/{id}")
    @HystrixCommand(fallbackMethod = "findByIdFallback", commandProperties =
         @HystrixProperty(name = "execution.isolation.strategy",value = "SEMAPHORE"))
    public User consumerFindUser(@PathVariable("id") Long id) {
        //service-provider是VIP虚拟ip
        User user = restTemplate.getForObject("http://service-user-noauth/findUser/" + id, User.class);
        log.info("调用了user服务");
        return user;
    }

    /**
     * 断路器
     *
     * @param id
     * @return
     */
    public User findByIdFallback(@PathVariable("id") Long id) {
        User user = new User();
        user.setId(0L);
        return user;
    }
}
